package com.bjpowernode.crm.web.controller;

import com.bjpowernode.crm.constants.Constants;
import com.bjpowernode.crm.pojo.Activity;
import com.bjpowernode.crm.pojo.ActivityRemark;
import com.bjpowernode.crm.service.ActivityService;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("act")
public class ActivityController {


    @Autowired
    private ActivityService activityService;

    @GetMapping("activities.json")
    // @RequestParam: 将参数封装成一个map对象，参数名作为map的key
    public List activities(@RequestParam Map conditions) {
        return activityService.getByConditions(conditions);
    }

    @PostMapping("save.do")
    public Map save(Activity activity) {
        System.out.println(activity);

        activityService.save(activity);

        return Constants.Result.SUC_WITH_MSG;
    }

    @GetMapping("activity.json")
    public Activity getById(String id) {
        return activityService.getById(id);
    }

    @PutMapping("edit.do")
    public Map edit(Activity activity) {
        activityService.edit(activity);

        return Constants.Result.SUC_WITH_MSG;
    }

    @PostMapping("import.do")
    public Map _import(MultipartFile upFile) throws IOException {
        HSSFWorkbook excel = new HSSFWorkbook(upFile.getInputStream());
        HSSFSheet sheet = excel.getSheetAt(0);
        int rowIndex = 1;
        Row row;

        List data = new ArrayList();

        while ((row = sheet.getRow(rowIndex++)) != null) {
            int cellIndex = 0;
            String name = row.getCell(cellIndex++).getStringCellValue();
            if (name == null || "".equals(name)) {
                continue;
            }

            String owner = row.getCell(cellIndex++).getStringCellValue();
            String startDate = row.getCell(cellIndex++).getStringCellValue();
            String endDate = row.getCell(cellIndex++).getStringCellValue();

            Activity activity = new Activity();
            activity.setName(name);
            activity.setOwner(owner);
            activity.setStartDate(startDate);
            activity.setEndDate(endDate);

            data.add(activity);
        }

        activityService.saveList(data);


        return Constants.Result.SUC_WITH_MSG;
    }


    @GetMapping("export.do")
    public void export(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 需要导出的数据
        List<Activity> list = activityService.getByConditions(null);

        // 创建一个空的excel文件
        HSSFWorkbook excel = new HSSFWorkbook();
        // 创建也签Sheet
        HSSFSheet sheet = excel.createSheet();
        // 创建行
        int rowIndex = 0;
        HSSFRow row = sheet.createRow(rowIndex++);
        // 创建单元格Cell
        int cellIndex = 0;
        row.createCell(cellIndex++).setCellValue("名称");
        row.createCell(cellIndex++).setCellValue("所有者");
        row.createCell(cellIndex++).setCellValue("开始日期");
        row.createCell(cellIndex++).setCellValue("结束日期");

        if (list != null && list.size() > 0) {
            for (Activity activity : list) {
                cellIndex = 0; // 每一行单元格的所有都从0开始

                row = sheet.createRow(rowIndex++);
                row.createCell(cellIndex++).setCellValue(activity.getName());
                row.createCell(cellIndex++).setCellValue(activity.getOwner());
                row.createCell(cellIndex++).setCellValue(activity.getStartDate());
                row.createCell(cellIndex++).setCellValue(activity.getEndDate());
            }


            String filename = "& * 市 场 活 动.xls";

            // 通过请求头中的User-Agent来判断浏览器类型
            String ua = request.getHeader("User-Agent");
            boolean IE_LT11 = ua.contains("MSIE"); // IE11以下版本
            boolean IE11 = ua.contains("rv:11.0) like Gecko"); // IE11
            boolean Edge = ua.contains("Edge"); // win10自带的Edge浏览器
            // 如果是微软的浏览器，直接进行UTF-8编码
            if (IE_LT11 || IE11 || Edge) {
                filename = URLEncoder.encode(filename, "UTF-8");
                // 编码之后空格变成+，替换回空格
                filename = filename.replace("+", " ");
            }
            // 标准浏览器使用Base64编码
            else {
                Base64.Encoder encoder = Base64.getEncoder();
                filename = encoder.encodeToString(filename.getBytes("utf-8"));

                // =?utf-8?B?文件名?= 是告诉浏览器以Base64进行解码
                filename = "=?utf-8?B?" + filename + "?=";
            }

            response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
            excel.write(response.getOutputStream());
        }
    }

    @GetMapping("remarks.json")
    public List remarks(String actId) {
        return activityService.getRemarks(actId);
    }


    @PostMapping("saveRemark.do")
    public Map saveRemark(ActivityRemark activityRemark) {
        if (activityRemark.getId() == null || "".equals(activityRemark.getId())) {
            activityService.saveRemark(activityRemark);
        } else {
            activityService.editRemark(activityRemark);
        }


        return Constants.Result.SUC_WITH_MSG;
    }

    @DeleteMapping("delRemark.do")
    public Map delRemark(String id) {
        activityService.delRemark(id);
        return Constants.Result.SUC_WITH_MSG;
    }
}
